package com.zhongxi.guoyuan.view;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.ImageBannerAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.user.center.UserCenterResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.view.personalCenter.BoxActivity;
import com.zhongxi.guoyuan.view.play.MoneyTreeActivity;
import com.zhongxi.guoyuan.view.play.RedPacketActivity;
import com.zhongxi.guoyuan.view.seller.SellerCenterActivity;
import com.zhongxi.guoyuan.view.update.UpdateActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.view.user.MyDividendActivity;
import com.zhongxi.guoyuan.view.user.gift.NewPersonGiftActivity;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.id;
import static com.baidu.location.g.h.I;
import static com.baidu.location.g.h.P;
import static com.baidu.location.g.h.T;
import static com.baidu.location.g.h.r;
import static com.baidu.location.g.h.v;
import static com.umeng.socialize.Config.dialog;

public class MainHomeActivity extends BaseActivity implements View.OnClickListener {

    private ViewFlow mViewFlow;
    private ImageBannerAdapter mBannerAdapter;
    private List<AdData> data = new ArrayList<AdData>();
    private TextView ivLocation;
    private ImageView ivDial;
    private ImageView ivMoneyTree;
    private ImageView ivRotate;
    private LinearLayout meibiShop;
    private LinearLayout goldShop;
    private LinearLayout bolivarBackShop;
    private LinearLayout bolivarShop;
    private ImageView ivImg;
    private TextView tvStoreHome;
    private String flag;

    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    private TextView tvStore;
    private TextView tvNum;
    private ImageView ivNewGift;
    private ImageView ivNewTips;
    private FrameLayout flow;
    private boolean isDialogShow = false;
    /**
     * 分红点数
     */
    int point = 0;
    public static final int requestSilver = 33;
    public static final int requestBoxSilver = 55;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_main_home);

        getPersimmions();

        ivLocation = (TextView) findViewById(R.id.ivLocation);
        ivLocation.setText(MyApplication.getInstance().getCity());

        ivNewGift = (ImageView) findViewById(R.id.ivNewGift);
        ivNewTips = (ImageView) findViewById(R.id.ivNewTips);
        ivRotate = (ImageView) findViewById(R.id.ivRotate);
        ivMoneyTree = (ImageView) findViewById(R.id.ivMoneyTree);
        ivDial = (ImageView) findViewById(R.id.ivDial);
        tvStore = (TextView) findViewById(R.id.tvStore);
        tvNum = (TextView) findViewById(R.id.tvNum);
        ivImg = (ImageView) findViewById(R.id.ivImg);
        //设置高度
        flow = (FrameLayout) findViewById(R.id.flow);
        ImageUtils.setHeight(this, Constants.flowRate, flow);

        //商城
        meibiShop = (LinearLayout) findViewById(R.id.meibiShop);
        goldShop = (LinearLayout) findViewById(R.id.goldShop);
        bolivarBackShop = (LinearLayout) findViewById(R.id.bolivarBackShop);
        bolivarShop = (LinearLayout) findViewById(R.id.bolivarShop);

        tvStoreHome = (TextView) findViewById(R.id.tvStoreHome);
    }

    /**
     * 初始化数据
     */
    private void initInfo() {
        if (null != MyApplication.getInstance().getAvatar() && !"".equals(MyApplication.getInstance().getAvatar())) {
            Glide.with(context).load(Url.BASE_URL + MyApplication.getInstance().getAvatar()).transform(new GlideRoundTransform(context, 10)).placeholder(R.mipmap.iv_eg).into(ivImg);
        }

        if (null != MyApplication.getInstance().getShopName() && !"".equals(MyApplication.getInstance().getShopName())) {
            tvStore.setText("店名：" + MyApplication.getInstance().getShopName());
        } else {
            tvStore.setText("店名：" + getString(R.string.app_name));
        }

        if (null != MyApplication.getInstance().getNum() && !"".equals(MyApplication.getInstance().getNum())) {
            tvNum.setText(getString(R.string.app_name) + "第" + MyApplication.getInstance().getNum() + "家网络分店");
        } else {
            tvNum.setText(getString(R.string.app_name) + "第*家网络分店");
        }

        if (MyApplication.getInstance().isShareHolders() || (MyApplication.getInstance().isPrivilege() && point > 0)) {  //股东或权益会员且股点不为零到分润看一看
            ivDial.setImageResource(R.mipmap.iv_super_man_profit);
        } else if (MyApplication.getInstance().isPrivilege()) {  //权益会员且股点为零,调到个人中心
            ivDial.setImageResource(R.mipmap.iv_upgrade);
        } else {
            ivDial.setImageResource(R.mipmap.iv_super_man);  //普通会员就是升级为权益会员
        }
    }

    private void lunbo() {
        try {
            //初始化轮播控件
            mViewFlow = (ViewFlow) findViewById(R.id.viewflow);
            CircleIndicator mViewIndic = (CircleIndicator) findViewById(R.id.viewflowdic);
            mViewFlow.setFlowIndicator(mViewIndic);

            if (data.size() > 0)
                mViewFlow.setSideBuffer(data.size()); // 实际图片数量
            if (mBannerAdapter == null) {
                mBannerAdapter = null;
                mBannerAdapter = new ImageBannerAdapter(this, data);
            } else {
                mBannerAdapter.replaceAll(data);
            }
            mViewFlow.setAdapter(mBannerAdapter);
            mViewFlow.startAutoFlowTimer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case SDK_PERMISSION_REQUEST:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    MyApplication.getInstance().mLocationClient.start();
                    ivLocation.setText(MyApplication.getInstance().getCity());
                } else {
                    // 没有获取到权限，做特殊处理
                }
                break;
            default:
                break;
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAd();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("ad".equals(flag)) {
                AdResult adResult = gson.fromJson(response, AdResult.class);
                MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                data.clear();
                data.addAll(adResult.getData());
                if (data.size() > 0) {
                    lunbo();
                }
                getUserInfo();
            } else if ("userinfo".equals(flag)) {
                UserCenterResult result = gson.fromJson(response, UserCenterResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
                sharedPrefrences.edit().putString("rmb", result.getUserExt().getRmb()).commit();
                sharedPrefrences.edit().putString("silver", result.getUserExt().getSilver()).commit();
                sharedPrefrences.edit().putString("inner", result.getUserExt().getInnercurrency()).commit();
                sharedPrefrences.edit().putString("avatar", result.getUserInfo().getAvatar()).commit();
                if (null != result.getUserExt().getId() && !"".equals(result.getUserExt().getId()))
                    sharedPrefrences.edit().putString("num", result.getUserExt().getId() + "").commit();
                if ("1".equals(result.getUserInfo().getIsprivilege())) {
                    sharedPrefrences.edit().putBoolean("privilege", true).commit();
                } else {
                    sharedPrefrences.edit().putBoolean("privilege", false).commit();
                }
                if ("1".equals(result.getUserInfo().getIsshareholders())) {
                    sharedPrefrences.edit().putBoolean("shareHolder", true).commit();
                } else {
                    sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
                }
                if (null != result.getRights() && result.getRights().size() > 0) {
                    for (int i = 0; i < result.getRights().size(); i++) {
                        if (result.getRights().get(i).getUsertype() == 1) {  //权益会员
                            if (null != String.valueOf(result.getRights().get(i).getSharesnum()))
                                point += result.getRights().get(i).getSharesnum();  //权益会员分红点数
                        }
                    }
                }

                if (!TextUtils.isEmpty(MyApplication.getInstance().getUserId()) && result.getBackSilver() > 0 && result.getUpdRights() != 1) {
                    showGetBackSilverDialog(result.getBackSilver());
                }

                if (!TextUtils.isEmpty(MyApplication.getInstance().getUserId()) && result.getBackSilver() <= 0 && result.getUpdRights() == 1) {
                    showMemberDialog();
                }

                if (!TextUtils.isEmpty(MyApplication.getInstance().getUserId()) && result.getBackSilver() > 0 && result.getUpdRights() == 1) {
                    showBackSilverMember(result.getBackSilver());
                }
                initInfo();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 弹出即使权益会员又有返银币的弹窗
     *
     * @param backSilver
     */
    private void showBackSilverMember(int backSilver) {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        final AlertDialog dag = adb.create();
        View view = View.inflate(this, R.layout.dialog_backsilver_member, null);
        ImageView ivCancle = (ImageView) view.findViewById(R.id.iv_member_cancle);
        TextView tvSilverNumber = (TextView) view.findViewById(R.id.tv_silver_number);
        tvSilverNumber.setText(backSilver + "银币");
        TextView tvSure = (TextView) view.findViewById(R.id.tv_sure);
        ivCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dag.dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dag.dismiss();
                Intent intent = new Intent(MainHomeActivity.this, UpdateActivity.class);
                intent.putExtra("member", 1);
                startActivityForResult(intent, requestSilver);
            }
        });
        dag.setView(view);
        dag.show();
    }

    /**
     * 弹出为升级为权益会员的弹窗
     */
    private void showMemberDialog() {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        final AlertDialog dialog = adb.create();
        View view = View.inflate(this, R.layout.dialog_member, null);
        ImageView ivCancle = (ImageView) view.findViewById(R.id.iv_member_cancle);
        TextView tvMemberSure = (TextView) view.findViewById(R.id.tv_member_sure);
        ivCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tvMemberSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(MainHomeActivity.this, UpdateActivity.class);
                intent.putExtra("member", 1);
                startActivityForResult(intent, requestSilver);
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    /**
     * 返银币弹窗
     *
     * @param backSilver
     */
    private void showGetBackSilverDialog(int backSilver) {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        final AlertDialog dialog = adb.create();
        View view = View.inflate(this, R.layout.dialog_back_silver, null);
        ImageView ivCancle = (ImageView) view.findViewById(R.id.iv_back_sliver_cancle);
        TextView tvNumber = (TextView) view.findViewById(R.id.tv_back_silver_number);
        TextView tvSure = (TextView) view.findViewById(R.id.tv_back_silver_sure);
        tvNumber.setText(backSilver + "银币");
        ivCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(MainHomeActivity.this, BoxActivity.class);
                intent.putExtra("index", 3);
                startActivityForResult(intent, requestBoxSilver);
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
            flag = "userinfo";
            getServer(Url.USER_CENTER, null, "", false, null, "get");
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    /**
     * 获取广告轮播图
     */
    private void getAd() {
        flag = "ad";
        String getStr = "&type=1";
        getServer(Url.SHOW_ADS, null, getStr, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivRotate.setOnClickListener(this);
        ivMoneyTree.setOnClickListener(this);
        ivDial.setOnClickListener(this);
        meibiShop.setOnClickListener(this);
        goldShop.setOnClickListener(this);
        bolivarBackShop.setOnClickListener(this);
        bolivarShop.setOnClickListener(this);
        tvStoreHome.setOnClickListener(this);
        ivNewGift.setOnClickListener(this);
        ivNewTips.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(context, MainActivity.class);
        switch (view.getId()) {
            case R.id.ivRotate:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    startAct(MoneyTreeActivity.class);
                } else {
//                    showShortToast("用户未登录，请先登录");
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.ivMoneyTree:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    startAct(RedPacketActivity.class);
                } else {
//                    showShortToast("用户未登录，请先登录");
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.ivDial:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    if ((MyApplication.getInstance().isPrivilege() && point > 0) || MyApplication.getInstance().isShareHolders()) {
                        ivDial.setImageResource(R.mipmap.iv_super_man_profit);
                        startAct(MyDividendActivity.class);//分红看一看
                    } else if (MyApplication.getInstance().isPrivilege()) {
                        ivDial.setImageResource(R.mipmap.iv_upgrade);
                        showShortToast("您已成为权益会员");
                    } else {
                        ivDial.setImageResource(R.mipmap.iv_super_man);
                        startAct(UpdateActivity.class);//升级为权益会员
                    }
                } else {
                    showShortToast("请先登录");
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.meibiShop:
                intent.putExtra("index", 0);
                startActivity(intent);
                break;
            case R.id.goldShop:
                intent.putExtra("index", 1);
                startActivity(intent);
                break;
            case R.id.bolivarBackShop:
                intent.putExtra("index", 2);
                startActivity(intent);
                break;
            case R.id.bolivarShop:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    intent.putExtra("index", 3);
                    startActivity(intent);
                } else {
                    Intent loginIntent = new Intent(context, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                }
                break;
            case R.id.tvStoreHome:
                startAct(SellerCenterActivity.class);
                break;
            case R.id.ivNewGift:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    startAct(NewPersonGiftActivity.class);
                } else {
                    Intent loginIntent = new Intent(context, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                }
                break;
            case R.id.ivNewTips:
                startAct(NewTipsActivity.class);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestSilver && resultCode == UpdateActivity.ResultSilver) {
            getUserInfo();
        } else if (requestCode == requestBoxSilver && resultCode == BoxActivity.resultBoxSiler) {
            getUserInfo();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            SharedPreferences sharedPreferences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            sharedPreferences.edit().putString("credentials", "").commit();
            sharedPreferences.edit().putString("beautifulcredentials", "").commit();
            sharedPreferences.edit().putString("beautifulcredentials", "").commit();
            sharedPreferences.edit().putString("rewardcoincredentials", "").commit();
            sharedPreferences.edit().putString("coincredentials", "").commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
